import { createStore, createLogger } from 'vuex'
import axios from 'axios'
import { Dialog } from 'vant';
// 列表类型
export interface ListItemType {
  'title': string,
  'desc': string,
  'price': number,
  'id': string,
  'url': string,
}

// 购物车类型 包含  列表类型
export interface CarListType extends ListItemType {
  count: number
  isChecked: boolean
}


export interface StateType {
  list: ListItemType[],
  car: CarListType[]
}


export default createStore<StateType>({
  state: {
    list: [],
    car: []
  },
  mutations: {
    setList(state, payload: ListItemType[]) {
      state.list = payload
    },
    addCar(state, payload: ListItemType) {
      const item = state.car.find(v => v.id === payload.id)

      if (item) {
        item.count++
      } else {
        state.car = [...state.car, { ...payload, count: 1, isChecked: false }]
      }
    },
    subCar(state, payload: ListItemType) {
      const item = state.car.find(v => v.id === payload.id);
      if (item) {
        if (item.count <= 1) {
          // 删除
          Dialog.confirm({
            title: '警告',
            message: '确认要删除该商品吗？',
          }).then(() => {
            state.car = state.car.filter(v => v.id !== item.id)
          })
        } else {
          // 正常减少
          item.count--
        }
      }
    }
  },
  getters: {
    totalCount(state) {
      return state.car.reduce((p, n) => {
        return p + n.count
      }, 0)
    }
  },
  actions: {
    async fetch_list({ commit }) {
      const resp = await axios.get('/api/list')
      // commit({ type: 'setList', payload: resp.data.data })
      commit('setList', resp.data.data)
    }
  },
  modules: {
  },
  plugins: [createLogger()]
})
